package com.wontube.core.utils;

import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.wontube.core.pub.AppEnvironment;


/** 
 * @author tanggf(2012-4-5)
 *
 */
public class JsonUtils {
	/**
	 * 从url流生成gson的JsonObject对象
	 * @param url
	 * @return
	 */
	public static JsonObject getJsonObjectFromUrl(String url){
		HttpURLConnection conn = null;
		InputStreamReader reader = null;
		JsonObject jsonObject = null;
		try {
			URL uri = new URL(url);
			conn = (HttpURLConnection) uri.openConnection();
			conn.connect();
			reader = new InputStreamReader(conn.getInputStream(), AppEnvironment.charsetName);
			JsonParser parser = new JsonParser();
			jsonObject = (JsonObject) parser.parse(reader);
		} catch (Exception e) {
			//重抛成runtime exception
			throw new RuntimeException(e);
		}finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (Exception e2) {					
				}				
			}
			if(conn != null){
				conn.disconnect();
			}			
		}
		return jsonObject;
	}
}
